﻿using System;
using System.Windows;
using System.Windows.Media;
using System.Collections.Generic;
using Simp.CodeModel;
using System.Windows.Controls;

namespace Simp.GraphModel
{
	/// <summary>Contains methods helping to manipulate <see cref="IFunction"/> in the context of the graph modelling.</summary>
	public static class GraphicHelper
	{
		/// <summary>Empty array of <see cref="FrameworkElement"/>.</summary>
		public static readonly FrameworkElement[] EmptyElements = new FrameworkElement[0];

		/// <summary>Default stroke <see cref="Brush"/>.</summary>
		public static readonly Brush DefaultStroke = new SolidColorBrush(Colors.Red);

		/// <summary>Produces a UI element from a function.</summary>
		/// <param name="function"></param>
		/// <param name="parameters"></param>
		/// <returns></returns>
		public static UIElement Produce(IFunction function, params IFunction[] parameters)
		{
			IElementProducerFunction elementProducer = function as IElementProducerFunction;

			if (elementProducer == null)
			{
				BoundFunctionCalling boundFunction =
					FunctionHelper.TryGetBoundFunction<IElementProducerFunction>(function, out elementProducer);

				if (boundFunction == null)
				{
					return null;
				}
				else
				{
					return elementProducer.Produce(boundFunction.FunctionParameters);
				}
			}
			else
			{
				return elementProducer.Produce(parameters);
			}
		}

		/// <summary>
		/// Add a transform on a ui-element.  If the ui element already has a transform, it appends the transformations.
		/// </summary>
		/// <param name="uiElement"></param>
		/// <param name="transform"></param>
		public static void AddTransform(UIElement uiElement, Transform transform)
		{
			if (MatrixTransform.Identity.Equals(uiElement.RenderTransform))
			{
				uiElement.RenderTransform = transform;
			}
			else
			{
				TransformGroup group = uiElement.RenderTransform as TransformGroup;

				if (group == null)
				{
					group.Children.Add(transform);
				}
				else
				{
					group = new TransformGroup();
					group.Children.Add(uiElement.RenderTransform);
					group.Children.Add(transform);
					uiElement.RenderTransform = group;
				}
			}
		}
	}
}